// 关系型数据库类型
var jdbcTypeCode=["1","2","3","4","5","6","8"];
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'datasource/database/list',
        datatype: "json",
        mtype: "POST",
        colModel: [			
			{ label: '编号', name: 'id', index: 'id', width: 50, key: true },
			{ label: '数据源名称', name: 'name', index: 'name', width: 80 },
			{ label: '类型', name: 'typeName', index: 'type', width: 80 },
			{ label: '描述', name: 'remarks', index: 'remarks', width: 80 },
			{ label: '所属机构', name: 'deptName', width: 80 }
        ],
		viewrecords: true,
        height: 'auto',
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        //width: document.body.clientWidth,根据body的宽度使用这个请注释掉autowidth:true
        // multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "data.data",
            page: "data.pageNum",
            total: "data.pages",
            records: "data.recordCounts"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        postData:{'spaceId': getCookie("user_space_id"),type: getQueryString('type')},
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    $("#jqGrid").filterToolbar({}).jqGrid('navGrid',"#jqGridPager",{//刷新按钮
        refresh: true,
        edit:false,del: false,search:false,add:false
    });

    vm.loadSpace();
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;

function showJDBC(val){
    // 判断是否通用关系型数据库
    if($.inArray(val, jdbcTypeCode) != -1){
        vm.showJDBC = true;
        vm.showNoSql = false;
    }else{
        vm.showJDBC = false;
        vm.showNoSql= true;
    }
    vm.showMysqlJDBC = false;
    vm.showOceaBaseJDBC = false;
    vm.showOracleJDBC = false;
    vm.showMongoDb = false;
    vm.showHbaseDb = false;
    vm.showHiveJDBC = false;
    vm.showIsPub = false;

    if(val == 1 || val == 3 || val == 4 || val == 5 || val == 8){
        //判断是否是Mysql=1
        vm.showMysqlJDBC = true;
        if(val == 8){
            vm.showHiveJDBC = true;
        }
        if(val == 1){
            vm.showIsPub = true;
        }
    }else if(val == 6){
        vm.showOceaBaseJDBC = true;
    }else if(val == 2){
        // 判断是否Oracle=2
        vm.showOracleJDBC = true;
    }else if(val == 7){
        vm.showMongoDb = true;
    }else if(val == 9){
        vm.showHbaseDb = true;
    }
}
var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        showJDBC: false,
        showNoSql: false,
        showOracleJDBC: false,
        showMysqlJDBC: false,
        showOceaBaseJDBC: false,
        showMongoDb: false,
        showHiveJDBC: false,
        showHbaseDb: false,
        showIsPub: false,
		title: null,
        spaceList: [],
		database: {
		    oracleType:"200",
            deptId:null,
            deptName:null,
            clusterName: "",
            tenantName: "",
            dbName:"",
            url:""
		}
	},
	methods: {
		query: function () {
			vm.reload();
		},
        loadSpace: function(){
            $.ajax({
                type: "POST",
                url: baseURL + "workspace/space/list",
                contentType: "application/json",
                header: {limit: 100000},
                data: {},
                success: function(r){
                    if(r.code === 0){
                        vm.spaceList = r.data.data;
                    }else{
                        layer.alert(r.msg);
                    }
                }
            });
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
            vm.database = {deptName:null, deptId:null, type: -1, oracleType: "200", spaceId:getCookie("user_space_id")};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
		    if((vm.database.clusterName=="" && vm.database.tenantName != "") ||
                (vm.database.clusterName!="" && vm.database.tenantName == "")){
		        layer.alert("数据源配置错误！集群名和租户名应同时使用，或者均不填。");
		        return;
            }
            var url = vm.database.id == null ? "datasource/database/save" : "datasource/database/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.database),
                success: function(r){
                    if(r.code === 0){
                        layer.msg("操作成功", {icon: 1});
                        vm.reload();
                    }else{
                        layer.alert(r.msg);
                    }
                }
            });
		},
		del: function (event) {
			var ids = [];
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			ids.push(id);
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "datasource/database/deleteBatch",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(id){
			$.get(baseURL + "datasource/database/info/"+id, function(r){
                if(r.code == 0){
                    vm.database = r.data;
                    showJDBC(r.data.type);
                }else{
                    alert(r.msg);
                }
            });
		},
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '10px',
                skin: 'layui-layer-molv',
                title: "选择部门",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级部门
                    vm.database.deptId = node[0].deptId;
                    vm.database.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },
        changeDbType: function(event){
		    var val = event.target.value;
            vm.database.isPub = false;
            showJDBC(val);
        },
        testConn: function(){
            $.ajax({
                type: "POST",
                url: baseURL + "datasource/database/testConn",
                contentType: "application/json",
                data: JSON.stringify(vm.database),
                success: function(r){
                    if(r.code === 0){
                        layer.msg(r.msg, {icon: 1});
                        $('#btnSaveOrUpdate').button('reset');
                        $('#btnSaveOrUpdate').dequeue();
                    }else{
                        layer.alert(r.msg);
                        $('#btnSaveOrUpdate').button('reset');
                        $('#btnSaveOrUpdate').dequeue();
                    }
                }
            });
        },
		reload: function (event) {
			vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'spaceId': getCookie("user_space_id"), type: getQueryString('type')},
                page:page
            }).trigger("reloadGrid");
		}
	}
});